#include "Game.h"
#include "GameState.h"

// Destructor
Game::~Game()
{
}

void Game::Init(const char* title, int width, int height, int bpp, bool fullscreen)
{
	int flags = 0;

	// Initialize SDL
	SDL_Init(SDL_INIT_EVERYTHING);

	// Set the title bar text
	SDL_WM_SetCaption(title, title);

	if (fullscreen) {flags = SDL_FULLSCREEN;}

	// Create the screen surface
	m_pScreen = SDL_SetVideoMode(width, height, bpp, flags);

	m_bFullscreen = fullscreen;
	m_bRunning = true;

	// Print our success
	printf("Game Initalized Successfully\n");
}

// ChangeState() takes a pointer to a GameState as a parameter and then pushes that state onto the vector
// of pointers to GameStates, before that it uses the clean function to remove the old state from the stack
void Game::ChangeState(GameState* state)
{
	// Cleanup the current state
	if(!states.empty()) {
		states.back()->Clean();
		states.pop_back();
	}

	// Store and init the new state
	states.push_back(state);
	states.back()->Init();
}

// PushState() pauses the previous state before pushing a new state onto
// the stack. This state can then be removed and the previous state resumed.
// Useful for pausing
void Game::PushState(GameState* state)
{
	// Pause current state
	if(!states.empty()) {
		states.back()->Pause();
	}

	// Store and init the new state
	states.push_back(state);
	states.back()->Init();
}

// Remove and resume previous state
void Game::PopState()
{
	// Cleanup the Current state
	if(!states.empty()) {
		states.back()->Clean();
		states.pop_back();
	}

	// Resume previous state
	if(!states.empty()) {
		states.back()->Resume();
	}
}

// These functions now allow the current state to handle things
// states.back() refers to the last element on the stack (the current state)

void Game::HandleEvents()
{
	// Let the state handle it
	states.back()->HandleEvents(this);
}

void Game::Update()
{
	// Let the state handle it
	states.back()->Update(this);
}

void Game::Draw()
{
	// Let the state handle it
	states.back()->Draw(this);
	//SDL_Flip(m_pScreen);
}

void Game::Clean()
{
	while(!states.empty()) {
		states.back()->Clean();
		states.pop_back();
	}

	// Shutdown SDL
	SDL_Quit();
}